/**
 * 包裹
 */
 class Bag extends PIXI.Container {
	constructor() {
		super();
		this.items = {};
		this.amounts = {};
		this.applys = {};
		this.gold = 0;
		this._opationIndex = -1;

		// 添加菜单
		this.menu = new Menu("ITEM", 420, 170);
		this.addChild(this.menu);

		// 顶部选单
		this.opations = new PIXI.Container();
		this.addChild(this.opations);

		// 添加左右按钮
		const leftButton = new Button("←", {width:24,height:18});
		leftButton.x = 70;
		leftButton.y = -4;
		this.addChild(leftButton);
		
		this.rightButton = new Button("→", {width:24,height:18});
		this.rightButton.x = 248;
		this.rightButton.y = -4;
		this.addChild(this.rightButton);
	}

	test() {
		function createTestItem(index) {
			const item = new Item();
			item.name = "测试道具" + index;
			item.itemType = 0;
			item.location = 0;
			item.url = "w"+index;
			return item;
		}

		function createTestItem2(index) {
			const item = new Item();
			item.name = "测试道具" + index;
			item.itemType = 0;
			item.location = 1;
			item.url = "a"+index;
			return item;
		}

		for(var i = 0; i < 10; i++) {
			this.items["w"+i] = createTestItem(i);
			this.amounts["w"+i] = 1;
			this.applys["w"+i] = 0;
		}

		for(var i = 0; i < 10; i++) {
			this.items["a"+i] = createTestItem2(i);
			this.amounts["a"+i] = 1;
			this.applys["a"+i] = 0;
		}
	}

	get opationIndex() {
		return this._opationIndex;
	}

	hideButtons() {
		
	}

	addOpation(icon, location, isSelected) {
		
		const c = new PIXI.Container();
		const x = this.opations.children.length * 24;

		c.location = location;
		c.x = 100 + x;
		c.y = -4;

		// 选框
		const box = new PIXI.smooth.SmoothGraphics();
		box.beginFill(isSelected ? 0xC8C090 : 0x889858, 1);
		box.lineStyle({ color: isSelected ? 0xF0F0B8 : 0x587038, width: 2, alignment: 0 });
		box.drawRect(0,0,24,24);
		box.endFill();
		box.lineStyle({ color: isSelected ? 0x605008 : 0x384018, width: 2, alignment: 0 });
		box.moveTo(22,24).lineTo(22,0);
		box.moveTo(24,24).lineTo(0,24);
		c.addChild(box);

		// icon
		const iconSprite = new PIXI.Sprite(PIXI.Texture.from(icon));
		iconSprite.x = 4;
		iconSprite.y = 4;
		iconSprite.tint = {r:32,g:32,b:32};
		c.addChild(iconSprite);

		this.opations.addChild(c);
	}

	updateOpations(selected, onlyShowEquips) {
		for(var i = 0; i < this.opations.children.length; i++) {
			this.opations.removeChild(this.opations.children[i]);
			i--;
		}

		this.addOpation("res/system/weapon.png", 0, selected == 0);
		this.addOpation("res/system/shield.png", 1, selected == 1);
		this.addOpation("res/system/armor.png", 2, selected == 2);
		this.addOpation("res/system/adornment.png", 3, selected == 3);
		if(!onlyShowEquips) {
			this.addOpation("res/system/usable.png", 3, selected == 4);
			this.addOpation("res/system/others.png", 3, selected == 5);
			this.rightButton.x = 248;
		}
		else {
			this.rightButton.x = 201;
		}
	}

	async selectOpation(index, items) {
		if(this._opationIndex==index)
			return;

		this._opationIndex = index;
		this.updateOpations(index, this._onlyShowEquips);

		var items;
		switch(index) {
			case 0: items = await new Promise(resolve => this.getEquipmentList(0, resolve)); break;
			case 1: items = await new Promise(resolve => this.getEquipmentList(1, resolve)); break;
			case 2: items = await new Promise(resolve => this.getEquipmentList(2, resolve)); break;
			case 3: items = await new Promise(resolve => this.getEquipmentList(3, resolve)); break;
			case 4: items = await new Promise(resolve => this.getUsableList(resolve)); break;
			case 5: items = await new Promise(resolve => this.getOtherList(resolve)); break;
		}

		this.menu.clearItems();

		for(var i = 0; i < items.length; i++) {
			const item = items[i];
			const menuItem = new MenuItem(item.name);
			menuItem.enable = this.enableFunc(item);
			menuItem.icon = item.getIcon();
			
			// 添加当前index/total
			const length = `${this.apply(item.url, 0)}/${this.amounts[item.url]||0}`;
			const size = PIXI.TextMetrics.measureText(length, menuItem.enable ? textStyle : unenableStyle).width;
			const literal = new PIXI.Text(length, menuItem.enable ? textStyle : unenableStyle);
			literal.x = 410 - size;
			literal.y = 0;
			literal.resolution = 2;

			if(this._showPrice) {
				const textContainer = new PIXI.Container();
				const price = `${parseInt(item.price * this._priceRadio)}$`;
				const priceLiteral = new PIXI.Text(price, menuItem.enable ? textStyle : unenableStyle);
				priceLiteral.x = 410 - 120;
				priceLiteral.y = 0;
				priceLiteral.resolution = 2;

				textContainer.addChild(literal);
				textContainer.addChild(priceLiteral);
				menuItem.connectContrl = textContainer;
			}
			else {
				menuItem.connectContrl = literal;
			}

			this.menu.addItem(menuItem);
		}

		this.showItems = items;
		if(this.showItems.length > 0) 
			this.menu.selectedIndex = 0;
	}

	setup(enableFunc, zFunc, xFunc, onlyShowEquips, showPrice, priceRadio, items, opationIndex) {
		this._sellItems = items;
		this.enableFunc = enableFunc;
		this.xFunc = xFunc;
		this.zFunc = zFunc;
		this._showPrice = showPrice ?? false;
		this._priceRadio = priceRadio ?? 1;
		this._onlyShowEquips = onlyShowEquips ?? true;
		this._opationIndex = -1;
		this.selectOpation(opationIndex ?? 0);
		this.menu.selectedIndex = 0;

		if(this.descrption)
			this.descrption.reset();

		if(showPrice) {
			if(!this.priceText) {
				// 添加price
				const headLiteral = "PIRCE";
				this.priceText = new PIXI.Text(headLiteral, panelHeadStyle);
				this.priceText.x = this.width - 130;
				this.priceText.y = 2;
				this.priceText.resolution = 2;
				this.addChild(this.priceText);
			}	
		}
		else {
			if(this.priceText) {
				this.removeChild(priceText);
			}
		}
	}

	keyDown(key) {
		switch(key) {
			case "left": this.selectOpation(Math.max(0, this._opationIndex - 1)); break;
			case "right": this.selectOpation(Math.min(5, this._opationIndex + 1)); break;
			case "up": 
				this.menu.up();
				if(this.descrption) 
					this.descrption.show(this.showItems[this.menu.selectedIndex].descrption);
				break;
			case "down": 
				this.menu.down(); 
				if(this.descrption) 
					this.descrption.show(this.showItems[this.menu.selectedIndex].descrption);
				break;
			case "a":
				break;
			case "s":
				if(!this.descrption) {
					// 添加描述控件
					this.descrption = new Descrption(L2D.UIManager);
					this.addChild(this.descrption);
				}

				if(!this.descrption.visual)
					this.descrption.show(this.showItems[this.menu.selectedIndex].descrption);
				else
					this.descrption.close();
				break;
			case "z":
				if(!this.menu.selected.enable) {
					return;
				}

				this.zFunc(this.showItems[this.menu.selectedIndex]); 
				break;
			case "x": this.xFunc(); break;
		}
	}

	/**
	 * 通知背包指定道具占用数量并返回应用后的数量
	 * @param {string} url 道具url 
	 * @param {int} amount 应用数量
	 * @return 返回当前应用数量
	 */
	apply(url, amount) {
		if(!this.items[url])
			this.items[url] = L2D.Loader.load(url);

		const exsitAmount = this.applys[url] ?? 0;
		this.applys[url] = exsitAmount + amount;
		return this.applys[url];
	}

	/**
	 * 向背包中添加指定道具
	 * @param {string} url 道具url 
	 * @param {int} amount 移除数量
	 */
	add(url, amount) {
		if(!this.items[url])
			this.items[url] = L2D.Loader.load(url);
			
		const exsitAmount = this.exist(url);
		this.amounts[url] = exsitAmount + amount;

		// 播放获得道具动画	

	}

	/**
	 * 从背包中移除指定道具
	 * @param {string} url 道具url
	 * @param {int} amount 添加数量 
	 */
	remove(url, amount) {
		const exsitAmount = this.exist(url);
	 	amount = Math.max(0, exsitAmount - amount);

		this.amounts[url] = amount;
		if(amount <= 0) {
			delete this.amounts[url];
		}
	}

	/**
	 * 查询指定道具是否存在于包裹中
	 * @param {string} url 道具url 
	 * @returns 当前道具数量
	 */
	exist(url) {
		if(this.amounts[url])
			return this.amounts[url];

		return 0;
	}

	/**
	 * 获取背包中装备列表
	 * @returns {Item[]} 返回道具实体
	 */
	async getEquipmentList(location, callback) {
		const items = [];
		if(this._sellItems) {
			for(var element in this._sellItems) {
				var item = await global.loadItem(this._sellItems[element].url);
				item = item.clone();
				item.price = this._sellItems[element].price ?? item.price;
				if(item.itemType == 0 && item.location == location) {
					items.push(item);
				}
			}
		}
		else {
			for(var element in this.amounts) {
				if(this.amounts[element] > 0) {
					if(this.items[element].itemType == 0 && this.items[element].location == location) {
						items.push(this.items[element]);
					}
				}
			}
		}
		callback(items);
	}

	/**
	 * 获取背包中消耗品列表
	 * @returns {Item[]} 返回道具实体
	 */
	async getUsableList() {
		const items = [];
		if(this._sellItems) {
			for(var element in this._sellItems) {
				var item = await global.loadItem(this._sellItems[element].url);
				item = item.clone();
				item.price = this._sellItems[element].price ?? item.price;
				if(item.itemType == 1) {
					items.push(item);
				}
			}
		}
		else {
			for(var element in this.amounts) {
				if(this.amounts[element] > 0) {
					if(this.items[element].itemType == 1) {
						items.push(this.items[element]);
					}
				}
			}
		}
		callback(items);
	}

	/**
	 * 获取背包中杂物列表
	 * @returns {Item[]} 返回道具实体
	 */
	async getOtherList() {
		const items = [];
		if(this._sellItems) {
			for(var element in this._sellItems) {
				var item = await global.loadItem(this._sellItems[element].url);
				item = item.clone();
				item.price = this._sellItems[element].price ?? item.price;
				if(item.itemType > 1) {
					items.push(item);
				}
			}
		}
		else {
			for(var element in this.amounts) {
				if(this.amounts[element] > 0) {
					if(this.items[element].itemType > 1) {
						items.push(this.items[element]);
					}
				}
			}
		}
		callback(items);
	}
}
